﻿Imports System.IO
Imports System.Data
Imports System.Resources

Public Class frmDataObsExport

    'La propriété public odatasource permet de mettre en mémoire la DataTable
    Dim x As Integer
    Dim DateNom As String
    Dim FichNom As String
    Dim lastSelectedPr As String
    Private rm As New ResourceManager(GetType(frmDataObsExport))
    Dim WithEvents rdPictureBox As DeviceApplication1.Button


    Public Function initCtlExport(ByVal selectedPr As String) As Boolean
      
        'Mise en place des boutons d'exports
        'Pour tous les exports du Protocole sélectionné

        Dim lstExports As List(Of ClsPrExport)
        Dim export As ClsPrExport
        Dim numBtn As Integer = 1
        Dim nbExport As Integer
        Dim expIsValid As Boolean = False
        '  Dim rdPictureBox As DeviceApplication1.Button = New DeviceApplication1.Button

        'Récupération de la liste des exports
        lstExports = DirectCast(frmEntryChoixProtocol.olistProtocoles.Protocols(selectedPr), clsProtocol).exports
        nbExport = lstExports.Count

        Try
            If (nbExport > 0) Then
                'Test si le protocole sélectionné a changé
                If (selectedPr = lastSelectedPr) Then
                    Return True
                End If

                'Netoyage du formulaire
                For Each ctl As Control In Me.Panel_BtnExports.Controls
                    If ctl.Name.Length > 6 Then
                        If ctl.Name.Substring(0, 7) = "btnExp-" Or ctl.Name.Substring(0, 4) = "lbl-" Then
                            Me.Panel_BtnExports.Controls.Remove(ctl)
                        End If
                    End If
                Next

                ''!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                '''''Le nom du format de l'export ne doit avoir que trois lettres !!!!!!!!!!!!!!!!!!!!!!
                'Création des boutons permettant l'export
                For Each export In lstExports
                    'Affichage du bouton
                    Select Case export.template.GetType.Name
                        Case "ClsPrExpTemplateCsv"
                            addNewExportBtn(numBtn, "csv", export.name)
                    End Select
                    numBtn = numBtn + 1
                Next
                expIsValid = True
            Else 'A voir si on ne met pas en place une politique d'export par défaut.....
                MsgBox(My.Resources.Images.alertPrExpNoExport, MsgBoxStyle.Critical, "Pocket eRelevé")
                expIsValid = False
            End If
            lastSelectedPr = selectedPr
        Catch ex As Exception
            MsgBox(ex.Message)
            Return False
        End Try
        Return expIsValid
    End Function

    Private Sub addNewExportBtn(ByVal numBtn As Integer, ByVal type As String, ByVal exportName As String)
        Dim rdExportLabel As System.Windows.Forms.Label
        ' creer 1 bouton
        rdPictureBox = New DeviceApplication1.Button
        rdPictureBox.Name = "btnExp-" & type & "-" & exportName
        rdPictureBox.BackColor = System.Drawing.Color.White
        rdPictureBox.Image = CType(My.Resources.Images.btnExportCSV, System.Drawing.Image)
        rdPictureBox.Size = New Size(89, 90)
        rdPictureBox.Anchor = AnchorStyles.Top
        'Label 
        rdExportLabel = New System.Windows.Forms.Label
        rdExportLabel.Name = "lbl-" & type & "-" & exportName
        rdExportLabel.Text = exportName
        rdExportLabel.Size = New Size(100, 20)
        rdExportLabel.TextAlign = ContentAlignment.TopCenter
        'Positionner
        rdPictureBox.Location = setBtnExpLocation(numBtn, True)
        rdExportLabel.Location = setBtnExpLocation(numBtn, False)
        AddHandler rdPictureBox.Click, AddressOf exportData
        Me.Panel_BtnExports.Controls.Add(rdPictureBox)
        Me.Panel_BtnExports.Controls.Add(rdExportLabel)

    End Sub

    Private Sub exportData(ByVal sender As Object, ByVal e As EventArgs)
        Dim myBtn As DeviceApplication1.Button = DirectCast(sender, DeviceApplication1.Button)
        Dim strExportName As String
        Dim strExportType As String
        Dim export As ClsPrExport = Nothing
        Dim strFileContent As String = ""
        Dim lstExports As List(Of ClsPrExport)
        'Récupération des données d'export (nom + type) à partir du nom du bouton
        Try
            strExportName = myBtn.Name.Split("-")(2)
            strExportType = myBtn.Name.Split("-")(1)
            'Récupération du nom de l'export --> récupérer l'object export concerné
            lstExports = DirectCast(frmEntryChoixProtocol.olistProtocoles.Protocols(lastSelectedPr), clsProtocol).exports
            For Each exp As ClsPrExport In lstExports
                If exp.name = strExportName And exp.format = strExportType Then
                    export = exp
                    Exit For
                End If
            Next
        Catch ex As Exception
            MsgBox(DirectCast(My.Resources.Images.errorOnSave, String) & " : " & ex.Message, MsgBoxStyle.Critical, "Pocket eRelevé")
        End Try

        ' a completer, appeler la methode export de ClsPrExpTemplateCsvSimple
        'Appel de la méthode d'export de l'objet export du protocole sélectionné
        'Création du fichier et sauvegarde des données
        If Not IsNothing(export) Then
            Try
                Dim val_retour As Boolean
                Dim oProtocolsToExport As Hashtable

                If FormMain.obervationsType = "current" Then
                    oProtocolsToExport = oProtocolsCurrentListObs
                Else
                    oProtocolsToExport = oProtocolsOldListObs
                End If

                strFileContent = export.template.exportAsString(DirectCast(oProtocolsToExport(lastSelectedPr), ClsListObservations), _
                                                   DirectCast(frmEntryChoixProtocol.olistProtocoles.Protocols(lastSelectedPr), clsProtocol).multiSpecies)
                val_retour = Fonctions.Export("", strFileContent, "Fichiers " & strExportType & " |*." & strExportType & " |Tous les fichiers|*.*")
                If val_retour Then
                    MsgBox(DirectCast(My.Resources.Images.AlertSaveOk, String), MsgBoxStyle.Information, "Pocket eRelevé")
                End If
            Catch ex As Exception
                MsgBox(DirectCast(My.Resources.Images.errorOnSave, String) & " : " & ex.Message, MsgBoxStyle.Critical, "Pocket eRelevé")
            End Try
        End If
    End Sub

    Private Function setBtnExpLocation(ByVal numBtn As Integer, ByVal isBtn As Boolean) As Point
        Dim xdec As Integer = 114
        Dim ydec As Integer = 110

        Dim xinit As Integer = 14
        Dim yinit As Integer = 105
        If isBtn Then
            xinit = 14
            yinit = 11
        End If

        Dim loc As Point
        If numBtn = 1 Then
            loc = New Point(xinit, yinit)
        ElseIf numBtn = 3 Then
            loc = New Point(xinit, yinit + ydec)
        ElseIf numBtn = 2 Then
            loc = New Point(xinit + xdec, yinit)
        ElseIf numBtn = 4 Then
            loc = New Point(xinit + xdec, yinit + ydec)
        End If
        Return loc
    End Function


    'Private Sub btnSauverXML_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    Dim StrT As String = ""
    '    'Previens quand la grid est vide
    '    If frmDataObsTable.dgGrid2.CurrentRowIndex = -1 Then
    '        MessageBox.Show(DirectCast(My.Resources.Images.alertNoData, String), "Pocket eRelevé")
    '        Exit Sub
    '        'Lorsque la Grid est non vide, la sauvegarde dans mes Documents en fichiers .xml
    '    Else
    '        Try
    '            ' Arra()
    '            ' StrT = FormMain.oListObs.ExportListObsTOXML()
    '            StrT = DirectCast(oProtocolsCurrentListObs(frmEntryChoixProtocol.selectedProtocolId), ClsListObservations).ExportListObsTOXML(DirectCast(oProtocolsCurrentListObs(indice), clsProtocol).multiSpecies)
    '            Export("", StrT, "Fichiers XML(xml)|*.nsml|Tous les fichiers|*.*")
    '            MsgBox(DirectCast(My.Resources.Images.AlertSaveOk, String), MsgBoxStyle.Information, "Pocket eRelevé")
    '        Catch ex As Exception
    '            MsgBox(DirectCast(My.Resources.Images.errorOnSave, String) & " : " & ex.Message, MsgBoxStyle.Critical, "Pocket eRelevé")
    '        End Try
    '    End If
    'End Sub

    'Private Sub btnSauverGPX_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    '    Dim StrT As String = ""

    '    'Previens quand la grid est vide
    '    If frmDataObsTable.dgGrid2.CurrentRowIndex = -1 Then
    '        MessageBox.Show(DirectCast(My.Resources.Images.alertNoData, String), "Pocket eRelevé")
    '        Exit Sub
    '        'Lorsque la Grid est nom vide, la sauvegarde dans mes Documents en fichiers .xml
    '    Else
    '        Try
    '            ' !!!! mettre a jour
    '            StrT = ExportObsXMLToGPX(FormMain.oListObs.ExportListObsTOXML())
    '            Export("", StrT, "Fichiers GPX(gpx)|*.gpx|Tous les fichiers|*.*")
    '            MsgBox(DirectCast(My.Resources.Images.AlertSaveOk, String), MsgBoxStyle.Information, "Pocket eRelevé")
    '        Catch ex As Exception
    '            MsgBox(DirectCast(My.Resources.Images.errorOnSave, String) & " : " & ex.Message, MsgBoxStyle.Critical, "Pocket eRelevé")
    '        End Try

    '    End If
    'End Sub

    'Private Sub btnSauverkml_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    '    'déclaration des strings qui contiendrons chaques balises de kml
    '    Dim strT As String

    '    If frmDataObsTable.dgGrid2.CurrentRowIndex = -1 Then
    '        MessageBox.Show(DirectCast(My.Resources.Images.alertNoData, String), "Pocket eRelevé")
    '        Exit Sub
    '    Else
    '        Try
    '            ' mettre a jour
    '            strT = ExportObsXMLToKML(FormMain.oListObs.ExportListObsTOXML())
    '            Export("", strT, "Fichiers KML(kml)|*.kml|Tous les fichiers|*.*")
    '            MsgBox(DirectCast(My.Resources.Images.AlertSaveOk, String), MsgBoxStyle.Information, "Pocket eRelevé")
    '        Catch ex As Exception
    '            MsgBox(DirectCast(My.Resources.Images.errorOnSave, String) & " : " & ex.Message, MsgBoxStyle.Critical, "Pocket eRelevé")
    '        End Try
    '    End If


    'End Sub

    'Private Sub btnSauverCSV_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    '    Dim StrT As String = String.Empty

    '    If frmDataObsTable.dgGrid2.CurrentRowIndex = -1 Then
    '        MessageBox.Show(DirectCast(My.Resources.Images.alertNoData, String), "Pocket eRelevé")
    '        Exit Sub
    '    Else
    '        Try
    '            ' mettre à jour le prot selectionné
    '            '  StrT = ExportObsXMLToCSV(DirectCast(oProtocolsListObs(frmEntryChoixProtocol.selectedProtocolId), ClsListObservations).ExportListObsTOXML())
    '            'StrT = (DirectCast(oProtocolsListObs(frmEntryChoixProtocol.selectedProtocolId), clsProtocol).exports.Item(0).format.
    '            '   StrT = ExportObsXMLToCSV(FormMain.oListObs.ExportListObsTOXML())
    '            Export("", StrT, "Fichiers CSV(csv)|*.csv|Tous les fichiers|*.*")
    '            MsgBox(DirectCast(My.Resources.Images.AlertSaveOk, String), MsgBoxStyle.Information, "Pocket eRelevé")
    '        Catch ex As Exception
    '            MsgBox("Sauvegarde impossible: " & ex.Message, MsgBoxStyle.Critical, "Pocket eRelevé")
    '        End Try
    '    End If
    'End Sub

    Private Sub btnRetour_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRetour2.Click
        Me.Hide()
        frmDataObsTable.Show()
    End Sub

    Private Sub btnMenu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMenu.Click
        Me.Hide()
        FormMain.Show()
    End Sub

End Class